package com.y2w.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.y2w.common.constant.AuthServerContant;
import com.y2w.common.exception.BizCodeEnum;
import com.y2w.common.utils.R;
import com.y2w.common.vo.MemberRespVo;
import com.y2w.gulimall.auth.fegin.MemberFeginService;
import com.y2w.gulimall.auth.fegin.ThirdPartFeginService;
import com.y2w.gulimall.auth.vo.UserLoginVo;
import com.y2w.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.y2w.common.constant.AuthServerContant.LOGIN_USER;


@Controller
public class LoginController {

    @Autowired
    ThirdPartFeginService thirdPartFeginService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeginService memberFeginService;

    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //接口防刷
        String redisCode=stringRedisTemplate.opsForValue().get(AuthServerContant.SMS_CODE_CACHE_PREFIX+phone);
        if(StringUtils.isNotBlank(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        int codeNum= (int) ((Math.random() * 9 + 1)*100000);
        String code = String.valueOf(codeNum);
        //验证码再次校检
        stringRedisTemplate.opsForValue().set(AuthServerContant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);

        thirdPartFeginService.sendCode(phone,code);
        return R.ok();
    }

    /**
     *
     * @param vo
     * @param result
     //* @param model
     * @param redirectAttributes 重定向携带数据,利用session原理
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         //Model model,
                         RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String,String> errors= result.
                    getFieldErrors().stream().
                    collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);//只能读取一次

            //校检出错，返回注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //真正注册，调用远程服务
        //校检验证码
        String code = vo.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerContant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(StringUtils.isNotBlank(redisCode)){

            if(code.equals(redisCode.split("_")[0])){
                stringRedisTemplate.delete(AuthServerContant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                R r = memberFeginService.regist(vo);
                if(r.getCode()==0){
                //    成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                //    失败
                    Map<String,String> errors= new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else{
                Map<String,String> errors= new HashMap<>();
                errors.put("code","验证码不匹配");
                redirectAttributes.addFlashAttribute("errors",errors);//只能读取一次

                //校检出错，返回注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String,String> errors= new HashMap<>();
            errors.put("code","验证码已过期或不存在");
            redirectAttributes.addFlashAttribute("errors",errors);//只能读取一次

            //校检出错，返回注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }


    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){

        //远程登录

        R r = memberFeginService.login(vo);
        if(r.getCode()==0){
            MemberRespVo respVo = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(LOGIN_USER,respVo);
            return "redirect:http://gulimall.com";
        }else{
            Map<String,String> errors=new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(LOGIN_USER);
        if(attribute==null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }

}
